package com.wyait.manage.idempotent.aop;

import com.wyait.manage.idempotent.annotations.FormPreIdempotent;
import com.wyait.manage.idempotent.token.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Package: com.wyait.manage.idempotent.aop
 * Description：防重复提交实现
 * Author: huangjian
 * Date:  2020/9/13 17:52
 * Modified By:
 *
 * @author huangjian
 */
@Component
@Slf4j
public class FormIdempotentAdvice implements MethodBeforeAdvice {

    @Resource
    private TokenManager tokenManager;

    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        try {
            if (method.isAnnotationPresent(FormPreIdempotent.class)) {
                log.info("FormIdempotentNewAspect进来了！");
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = servletRequestAttributes.getRequest();
                String token = tokenManager.getToken();
                request.setAttribute("X-Idempotent-Token", token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
